<template>
  <div class="mood-page">
    <t-navbar title="动态" :fixed="true"/>
    <!-- 顶部栏 -->
    <div class="top-bar">
      <span class="page-title">动态</span>
      <t-button
          size="small"
          theme="primary"
          shape="round"
          class="post-btn"
          @click="tzAdd"
      >
        <icon-font name="chat-add" class="btn-icon" />
        发动态
      </t-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <t-search
          v-model="searchMsg"
          shape="round"
          placeholder="请输入要搜索的动态内容"
          @change="searchMood"
      />
    </div>

    <!-- 话题推荐 -->
    <div class="topic-section">
      <div class="section-title">热门话题</div>
      <div class="topic-list">
        <div
            v-for="(topic, index) in topics"
            :key="index"
            class="topic-card"
            :style="{ backgroundImage: `url(${topic.bgImage})` }"
            @click="selectTopic(topic)"
        >
          <div class="topic-content">
            <div class="topic-name">#{{ topic.name }}</div>
            <div class="topic-desc">{{ topic.desc }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 动态列表 -->
    <div class="mood-list">
      <t-tabs v-model="activeTab" @change="changeTab">
        <t-tab-panel
            v-for="tab in tabs"
            :key="tab.value"
            :value="tab.value"
            :label="tab.label"
        >
          <mood-item :list="processedMoods" />
        </t-tab-panel>
      </t-tabs>
    </div>

    <!-- 悬浮按钮 -->
    <div class="float-action">
      <t-button shape="circle" theme="primary" @click="tzAdd">
        <icon-font name="chat-add" />
        <span style="font-size: 12px;">写动态</span>
      </t-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { get } from "../util/Request";
import MoodItem from "../components/MoodItem.vue";

// 定义动态项的接口
interface MoodItem {
  id?: string | number;
  content?: string;
  nickname?: string;
  imgurl?: string;
  imgurl1?: string;
  imgurl2?: string;
  imgurl3?: string;
  img1?: string;
  img2?: string;
  img3?: string;
  likes?: number;
  like?: boolean;
  views?: number;
  createTime?: string;
  [key: string]: any;
}

// 定义话题接口
interface Topic {
  name: string;
  desc: string;
  bgImage: string;
}

const router = useRouter();
const searchMsg = ref("");
const activeTab = ref("最新");
const moods = ref<MoodItem[]>([]);
const loading = ref(false);
const hasMore = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const isLoading = ref(false); // 标志当前是否正在加载数据

// 游戏分类
const gameTypes = ref([
  { id: 1, name: '英雄联盟' },
  { id: 2, name: '王者荣耀' },
  { id: 3, name: '和平精英' },
  { id: 4, name: '穿越火线' },
  { id: 5, name: '绝地求生' }
]);

// 话题推荐数据
const topics = ref<Topic[]>([
  {
    name: "每日打卡",
    desc: "记录你的每一天",
    bgImage: "https://bpic.588ku.com/back_pic/19/03/26/2255183ecd8ed8401662d6d757611de6.jpg",
  },
  {
    name: "游戏分享",
    desc: "分享你的游戏体验",
    bgImage: "https://bpic.588ku.com/Templet_origin_pic/05/21/17/7f72bca7f1f19e94d4bf44c2f4eac742.jpg",
  },
  {
    name: "心情日记",
    desc: "写下你的心情故事",
    bgImage: "https://img.tukuppt.com/png_preview/00/11/73/C1HBxBXIME.jpg",
  },
  {
    name: "技能交流",
    desc: "分享你的学习心得",
    bgImage: "https://bpic.588ku.com/ingram/22/12/12/240a68e75c803100651807781b252368.jpg",
  },
]);

const tabs = ref([
  { value: "最新", label: "最新动态" },
  { value: "热门", label: "热门动态" },
]);

// 默认封面图片
const DEFAULT_COVER_IMAGE = "https://peizhenba.oss-cn-hangzhou.aliyuncs.com/f702888f-3aeb-44e5-a307-6cd00317a3b6.png";

// 处理动态数据，确保每条动态都有封面图片
const processedMoods = computed(() => {
  return moods.value.map(mood => {
    // 检查是否有任何图片
    const hasAnyImage = mood.imgurl1 || mood.img1 || mood.imgurl2 || mood.img2 || mood.imgurl3 || mood.img3;
    return {
      ...mood,
      coverImage: hasAnyImage 
        ? (mood.imgurl1 || mood.img1 || mood.imgurl2 || mood.img2 || mood.imgurl3 || mood.img3) 
        : DEFAULT_COVER_IMAGE
    };
  });
});

// 加载数据
const loadData = (type: string, page: number) => {
  if (isLoading.value) return; // 如果正在加载，直接返回
  isLoading.value = true; // 设置为正在加载

  get(`mood/page?page=${page}&size=${pageSize.value}&type=${type}`,null).then((res: any) => {
    if (res.data.code === 200) {
      if (page === 1) {
        moods.value = res.data.data.data; // 如果是第一页，重置数据
      } else {
        moods.value.push(...res.data.data.data); // 否则追加数据
      }
      hasMore.value = res.data.data.data.length === pageSize.value; // 判断是否还有更多数据
    }
  }).finally(() => {
    isLoading.value = false; // 请求完成后重置标志
  });
};

// 处理滚动事件
const handleScroll = () => {
  const scrollTop = window.scrollY || document.documentElement.scrollTop;
  const windowHeight = window.innerHeight;
  const documentHeight = document.documentElement.scrollHeight;

  // 当滚动到页面底部时加载下一页
  if (scrollTop + windowHeight >= documentHeight - 50 && hasMore.value && !isLoading.value) {
    currentPage.value++; // 增加当前页数
    loadData(activeTab.value, currentPage.value); // 加载下一页数据
  }
};

// 搜索动态
const searchMood = () => {
  console.log("搜索内容:", searchMsg.value);
};

// 切换标签
const changeTab = (value: string) => {
  activeTab.value = value;
  currentPage.value = 1; // 重置当前页数
  loadData(value, currentPage.value); // 加载第一页数据
};

// 选择话题
const selectTopic = (topic: Topic) => {
  console.log("选择话题:", topic.name);
};

// 跳转到发布动态页面
const tzAdd = () => {
  router.push("/addmood");
};

// 初始化加载数据
onMounted(() => {
  loadData(activeTab.value, currentPage.value); // 加载第一页数据
  window.addEventListener('scroll', handleScroll); // 添加滚动事件监听器
});

// 移除事件监听器
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style scoped>
.mood-page {
  background: #f5f6fa;
  min-height: 100vh;
  padding: 16px;
  padding-bottom: 80px; /* 为底部导航栏预留空间 */
}

.top-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
}

.post-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
}

.btn-icon {
  margin-right: 4px;
}

.search-bar {
  margin-bottom: 16px;
}

.topic-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333; /* 修改文字颜色，避免和背景色相同 */
  margin-bottom: 12px;
}

.topic-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.topic-item {
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  height: 120px;
}

.topic-bg {
  width: 100%;
  height: 100%;
  object-fit: cover;
  filter: brightness(0.7);
}

.topic-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: white;
}

.topic-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
}

.topic-desc {
  font-size: 12px;
}
.mood-list {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.float-action {
  position: fixed;
  bottom: 100px; /* 调整悬浮按钮位置，避免与导航栏重叠 */
  right: 20px;
  z-index: 100;
}
</style>